package com.hns.can.master.common;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.hns.can.common.entity.BaseEntity;
import com.hns.tool.pub.PubUtil;

public abstract class AbstractImportByFile {
    
    protected abstract String getFileType();
    
    protected abstract List<Map<String, Object>> getListMapByFile(String file) throws Exception;
    
    protected abstract void dealProcessor(List<BaseEntity> baseEntitys) throws Exception;
    
    @SuppressWarnings("rawtypes")
    protected List<BaseEntity> doImport(Class object, String file) throws Exception {
        List<Map<String, Object>> dataMaps = getListMapByFile(file);//解析文件，得到数据，封装数据为List<Map<String, Object>>形式
        ArrayList<BaseEntity> baseEntitys = new ArrayList<BaseEntity>();
        for (Map<String, Object> dataMap : dataMaps) {
            BaseEntity baseEntity = (BaseEntity) object.newInstance();
            BeanUtils.copyProperties(baseEntity, dataMap);
            baseEntitys.add(baseEntity);
        }
        return baseEntitys;
    }
    
    /**
     * @param object
     * @param file
     * @return
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-12-3
     * @功能说明：控制整个流程
     */
    @SuppressWarnings("rawtypes")
    public List<? extends BaseEntity> importFromFile(Class object, String file) throws Exception {
        if (!file.endsWith(getFileType())) {
            throw new Exception("文件格式不符合要求!");
        }
        List<BaseEntity> baseEntitys;
        try {
            baseEntitys = doImport(object, file);//解析文件，得到数据，并且将数据分装成List<BaseEntity>形式
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new Exception("读取文件构造对象BaseEntitys过程中出错:" + e.getMessage(), e);
        }
        dealProcessor(baseEntitys);//区别处理数据，重复性检查等等。。。
        if (PubUtil.isEmpty(baseEntitys)) {
            throw new Exception("该文件没有数据需要进行导入！");
        }
        return baseEntitys;
    }
    
}
